import $service from '../../../../../service.js';
var hospital_id = "1";
var that;
var inquiry_patient_id;
var doctor_id;
var druglistStorage_z = []; //已选中药处方 列表
var druglistStorage_x = []; //已选西药处方 列表
var that;
var StorageJosn;
var log_id;
var inquiryMap;
var prescriptionListlength = [];
// 西药开处方计算用Obj
var selectionunitNum=0;
var westernMedicinePrescriptionComputingObj = null;
Page({
    data: {
        drugMap: {},
        consumptionlist: [], //用量单位list
        list: [], //用法list
        list2: [], //频次list
        list3: [], //嘱托list
        details_usage: '', //用法
        details_consumption: '', //用量
        details_consumption_util: '', //用量单位
        details_frequency: '', ///频率,
        details_frequency_str: '',
        details_frequency_str2:'',
        details_day: '', //天数
        details_num: '', //盒数
        details_entrust: '', //嘱托
        islist: false,
        islist2: false,
        islist3: false,
        isconsumptionlist: false,
        drug_packaging_unit: '', //盒数单位
        getdruglistStoragelist: [], //已选处方
        isshow: 0,
        prescription_price: 0 ,//处方金额
        prescription_taking:'',//服用方法
        prescription_requirements:'',//服用要求
        prescription_num:'',//付数
        isdetalis:false,
        drug_type:0,
        frequency_num:0,
        frequency_day_num:0,
        selectionunit:0,
        drug_packaging_num:1,
    },
    onLoad(e) { //isshowType 1 开药 2 查看已选处方
        that = this.data;
        log_id = e.log_id
        if (e.isshowType == 1) {
            that.drugMap = $service.strToJson(e.drugMap)
        }
        this.setData({
            drugMap: that.drugMap,
            drug_type: e.drug_type,
            isshow: e.isshowType
        })
    },
    onShow() {
        that = this.data;
        doctor_id = $service.getUserLocalStorage().doctor_id;
        if (!$service.isUndefinedAndEmpty($service.getUserLocalStorage().hospital_id)) {
            hospital_id = $service.getUserLocalStorage().hospital_id
        }
        this.publicUtil_getInquiryLogDetails()
        this.publicUtil_getDrugDetail() //药品详情
        this.publicUtil_getUtilTable() //药品详情
        this.getdruglistStorage()
    },
    //问诊详情
    publicUtil_getInquiryLogDetails:function(){
        var jsonData ={
            "is_receive":"1",
            "log_id" : log_id
        }
        var jsonAjax = {
            "url": "publicUtil_getInquiryLogDetails.do",
            "jsonData": jsonData,
        }
        $service.getAjaxData(jsonAjax, this.publicUtil_getInquiryLogDetails_back);
    },
    //回调
    publicUtil_getInquiryLogDetails_back: function(jsonBack){
         var data=$service.strToJson(jsonBack.data).data;
         inquiryMap= data.inquiryMap; //患者信息
         prescriptionListlength= data.prescriptionList
    },
    
    getdruglistStorage() {
        if (that.drug_type == 1) { //1中药
            if(!$service.isUndefinedAndEmpty(wx.getStorageSync("druglistStorage_z" + doctor_id))){
                var list = $service.strToJson(wx.getStorageSync("druglistStorage_z" + doctor_id));
            }else {
                var list =[]
            }
            druglistStorage_z = list; //已选中药处方 列表

        } else if (that.drug_type == 2) {
            if(!$service.isUndefinedAndEmpty(wx.getStorageSync("druglistStorage_x" + doctor_id))){
                var list = $service.strToJson(wx.getStorageSync("druglistStorage_x" + doctor_id));
            }else{
                var list =[]
            }
            druglistStorage_x = list; //已选西药处方 列表
        }
        var drug_price=0;
        for(var i = 0; i < list.length;i++){
                if($service.isUndefinedAndEmpty(list[i].drug_price)){
                    list[i].drug_price = 0
                }
                if (that.drug_type == 1) { //1中药
                    drug_price+=$service.strToFloat(list[i].drug_price)*$service.strToInt(list[i].details_consumption);
                }else{
                    drug_price+=$service.strToFloat(list[i].drug_price)*$service.strToInt(list[i].details_num);
                }
                
        }
        this.setData({
            getdruglistStoragelist: list,
            prescription_price:drug_price
        })
    },
    //list
    publicUtil_getUtilTable: function() {
        if (that.drug_type == 2) {
            var type2 = "2,3,11"
        } else {
            var type2 = "6,7,8"
        }
        var jsonData = {
            "type": type2, //类型 // type 类型  1血糖测量条件 2西药药品用法 3药品使用频率 4系统医院 5科室表  6中药特殊服用用法 7中药服用方法 8中药服用要求
            "hospital_id": hospital_id, //医院id
        }
        var jsonAjax = {
            "url": "publicUtil_getUtilTable.do",
            "jsonData": jsonData,
        }
        $service.getAjaxData(jsonAjax, this.publicUtil_getUtilTable_back);
    },
    //回调
    publicUtil_getUtilTable_back: function(jsonBack) {
        var data = $service.strToJson(jsonBack.data).data;
        var list = data.list;
        if (!$service.isUndefinedAndEmpty(data.list2)) {
            that.list2 = data.list2
        }
        if (!$service.isUndefinedAndEmpty(data.list3)) {
            that.list3 = data.list3
        }
        this.setData({
            list: list,
            list2: that.list2,
            list3: that.list3
        })
    },
    //药品详情
    publicUtil_getDrugDetail: function() {
        var jsonData = {
            "drug_id": that.drugMap.drug_id
        }
        var jsonAjax = {
            "url": "publicUtil_getDrugDetail.do",
            "jsonData": jsonData,
        }
        $service.getAjaxData(jsonAjax, this.publicUtil_getDrugDetail_back);
    },
    //回调
    publicUtil_getDrugDetail_back: function(jsonBack) {
        var data = $service.strToJson(jsonBack.data).data;
        var drugMap = data.drugMap;
        westernMedicinePrescriptionComputingObj = drugMap;
        var drug_weight_num = $service.strToFloat(drugMap.drug_weight_num).toFixed(4)
        var drug_volume_num = $service.strToFloat(drugMap.drug_volume_num).toFixed(4)
        var drug_packaging_num = $service.strToFloat(drugMap.drug_packaging_num).toFixed(4)


        var consumption_utilHtml = [];

        if (drugMap.drug_type == "1") {
            if (!$service.isUndefinedAndEmpty(drugMap.drug_weight_unit)) {
                var jsonObj = {
                    "num" : '1',
                    "name" : drugMap.drug_weight_unit
                }
                consumption_utilHtml.push(jsonObj)
            }
            if (!$service.isUndefinedAndEmpty(drugMap.drug_volume_unit)) {
                var jsonObj = {
                    "num" : '2',
                    "name" : drugMap.drug_volume_unit
                }
                consumption_utilHtml.push(jsonObj)
            }
            if (!$service.isUndefinedAndEmpty(drugMap.drug_smallest_unit)) {
                var jsonObj = {
                    "num" : '3',
                    "name" : drugMap.drug_smallest_unit
                }
                consumption_utilHtml.push(jsonObj)
            }
            if (!$service.isUndefinedAndEmpty(drugMap.drug_packaging_unit)) {
                var jsonObj = {
                    "num" : '4',
                    "name" : drugMap.drug_packaging_unit
                }
                consumption_utilHtml.push(jsonObj)
            }
        } else {
            if (drug_weight_num > 0 && !$service.isUndefinedAndEmpty(drugMap.drug_weight_unit)) {
                var jsonObj = {
                    "num" : '1',
                    "name" : drugMap.drug_weight_unit
                }
                consumption_utilHtml.push(jsonObj)
            }
            if (drug_volume_num > 0 && !$service.isUndefinedAndEmpty(drugMap.drug_volume_unit)) {
                var jsonObj = {
                    "num" : '2',
                    "name" : drugMap.drug_volume_unit
                }
                consumption_utilHtml.push(jsonObj)
            }
            if (drug_packaging_num > 0 && !$service.isUndefinedAndEmpty(drugMap.drug_smallest_unit)) {
                var jsonObj = {
                    "num" : '3',
                    "name" : drugMap.drug_smallest_unit
                }
                consumption_utilHtml.push(jsonObj)
            }
        }

      var drug_weight_num = $service.strToFloat(drugMap.drug_weight_num).toFixed(4)
      var drug_volume_num = $service.strToFloat(drugMap.drug_volume_num).toFixed(4)
        this.setData({
            consumptionlist: consumption_utilHtml,
            drug_packaging_unit: drugMap.drug_packaging_unit,
           drug_packaging_num: drug_packaging_num,
          drug_weight_num: drug_weight_num,
          drug_volume_num: drug_volume_num,
        })
    },
    tap_usage(e) {
        var num = e.currentTarget.dataset.index;
        if (num == 0) { //用法
            that.islist = !that.islist
        } else if (num == 1) { //用量单位
            that.isconsumptionlist = !that.isconsumptionlist
        } else if (num == 2 || num == 4) { //频次
            that.islist2 = !that.islist2
        } else if (num == 3 || num == 5) { //嘱托
            that.islist3 = !that.islist3
        }
        this.setData({
            islist: that.islist,
            islist2: that.islist2,
            islist3: that.islist3,
            isconsumptionlist: that.isconsumptionlist
        })
    },
    //选择用法、用量单位、频次、嘱托
    chooselist(e) {
        var index = e.currentTarget.dataset.index;
        var num = e.currentTarget.dataset.num;
        if (num == 0) { //用法
            that.details_usage = that.list[index].usage_name
        } else if (num == 1) { //用量单位
            that.details_consumption_util = that.consumptionlist[index].name
            selectionunitNum = that.consumptionlist[index].num
          this.setData({
            selectionunit: index+1
          });
          this.jisuanxiyaochufangshuliang()
        } else if (num == 2) { //频次
            that.details_frequency = that.list2[index].frequency_id
            that.details_frequency_str = that.list2[index].frequency_printing_name
            that.details_frequency_str2 = that.list2[index].frequency_name

          this.setData({
            frequency_num: that.list2[index].frequency_num,
            frequency_day_num: that.list2[index].frequency_day_num
          });
          this.jisuanxiyaochufangshuliang()
        } else if (num == 3) { //嘱托
            that.details_entrust = that.list2[index].advice_name
        } else if (num == 4) { //服用方法
          that.prescription_taking = that.list2[index].usage_name
        } else if (num == 5) { //服用要求
          that.prescription_requirements = that.list2[index].usage_name
        }
        this.setData({
            details_usage: that.details_usage,
            details_consumption_util: that.details_consumption_util,
            details_frequency: that.details_frequency,
            details_frequency_str2:that.details_frequency_str2,
            details_frequency_str: that.details_frequency_str,
            details_entrust: that.details_entrust,
            prescription_taking: that.prescription_taking,
            prescription_requirements: that.prescription_requirements,
            islist: false,
            islist2: false,
            islist3: false,
            isconsumptionlist: false
        })
    },
    //input监听
    inputChange(e) {
        var index = e.currentTarget.dataset.index;
        if (index == 1) { //用量
            that.details_consumption = e.detail.value
        } else if (index == 2) { //天数
            that.details_day = e.detail.value
        } else if (index == 3) { //盒数
            that.details_num = e.detail.value
        } else if (index == 4) { //嘱托
            that.details_entrust = e.detail.value
        } else if (index == 5) { //付数
          that.prescription_num = e.detail.value
        }
        this.setData({
            details_consumption: that.details_consumption,
            details_day: that.details_day,
            details_num: that.details_num,
            details_entrust: that.details_entrust,
          prescription_num: that.prescription_num
        })
    },
    //input监听
    inputChange2(e) {
        var index = e.currentTarget.dataset.index;
        if (index == 1) { //用量
            that.details_consumption = e.detail.value
        } else if (index == 2) { //天数
            that.details_day = e.detail.value
        }else if(index == 5){
             that.prescription_num = e.detail.value
        }
        this.setData({
            details_consumption: that.details_consumption,
            details_day: that.details_day,
            prescription_num: that.prescription_num
        })
        if (index == 1) { //用量
          this.jisuanxiyaochufangshuliang()
        } else if (index == 2) { //天数
           this.jisuanxiyaochufangshuliang()
        }
    },
    tap_reduce_add(e) {
        var index = e.currentTarget.dataset.index;
        if ($service.isUndefinedAndEmpty(that.details_consumption)) {
            that.details_consumption = 0
        }
        if (index == 0) {
            that.details_consumption--
            if (that.details_consumption <= 0) {
                $service.showToast('用量不能小于0');
                that.details_consumption = 1
            }
        } else {
            that.details_consumption++
        }
        this.setData({
            details_consumption: that.details_consumption
        })
    },
    //生成处方
    qrBtn(e) {
        var index = e.currentTarget.dataset.index;
        if (index == 1) { //生成已选处方（未开）
            var detailsList = []
            if ($service.isUndefinedAndEmpty(that.details_consumption)) {
                $service.showToast('请先输入用量');
                return;
            }
            if (Number(that.details_consumption) <= 0) {
                $service.showToast('请先输入正确用量');
                return;
            }
            if ($service.isUndefinedAndEmpty(that.details_consumption_util)) {
                $service.showToast('请先选择用量单位');
                return;
            }

            if (that.drug_type == 1) { //1中药
                for (var i = 0; i < druglistStorage_z.length; i++) { //判断缓存是否有相同的，先删除再添加
                    if (druglistStorage_z[i].drug_id == that.drugMap.drug_id) {
                        druglistStorage_z.splice(i, 1)
                    }
                }
                StorageJosn = {
                    "details_consumption": that.details_consumption,
                    "details_consumption_util": that.details_consumption_util,
                    "details_usage": that.details_usage,
                    "drug_price": that.drugMap.drug_price,
                    "drug_name": that.drugMap.drug_name,
                    "drug_id": that.drugMap.drug_id
                }
                for (var i = 0; i < druglistStorage_z.length; i++) {
                    var drugid = {
                        "drug_id": druglistStorage_z[i].drug_id
                    }
                    detailsList.push(drugid)
                }
            } else { //2西药
                if ($service.isUndefinedAndEmpty(that.details_frequency)) {
                    $service.showToast('请先选择频次');
                    return;
                }
                if ($service.isUndefinedAndEmpty(that.details_day)) {
                    $service.showToast('请先输入天数');
                    return;
                }
                if (that.details_day > 90) {
                    $service.showToast('天数不能大于90天');
                    return;
                }
                if ($service.isUndefinedAndEmpty(that.drug_packaging_unit)) {
                    $service.showToast('请输入数量');
                    return;
                }
                if ($service.isUndefinedAndEmpty(that.details_usage)) {
                    $service.showToast('请选择用法');
                    return;
                }
                for (var i = 0; i < druglistStorage_x.length; i++) { //判断缓存是否有相同的，先删除再添加
                    if (druglistStorage_x[i].drug_id == that.drugMap.drug_id) {
                        druglistStorage_x.splice(i, 1)
                    }
                }
                StorageJosn = {
                    "details_consumption": that.details_consumption,
                    "details_consumption_util": that.details_consumption_util,
                    "details_frequency_str": that.details_frequency_str,
                    "details_frequency": that.details_frequency,
                    "details_day": that.details_day,
                    "details_num": that.details_num,
                    "details_usage": that.details_usage,
                    "details_entrust": that.details_entrust,
                    "drug_price": that.drugMap.drug_price,
                    "drug_name": that.drugMap.drug_name,
                    "drug_id": that.drugMap.drug_id
                }
                for (var i = 0; i < druglistStorage_x.length; i++) {
                    var drugid = {
                        "drug_id": druglistStorage_x[i].drug_id
                    }
                    detailsList.push(drugid)
                }
            }
            console.log(StorageJosn);
            var jsonData = {
                "hospital_id": hospital_id,
                "drug_id": that.drugMap.drug_id,
                "detailsList": $service.jsonToStr(detailsList)
            }
            var jsonAjax = {
                "url": "doctorSide_personal_prescription_getIncompatibility.do",
                "jsonData": jsonData,
            }
            $service.getAjaxData(jsonAjax, this.doctorSide_personal_prescription_getIncompatibility_back);
        }else if (index == 2) { //保存模板
            if (that.drug_type == 1) { //1中药
                var detailsList = druglistStorage_z;
            } else {
                var detailsList = druglistStorage_x;
            }
            if(detailsList.length == 0){
                $service.showToast('请先开处方');
                return;
            }
            $service.openPage('../../index_template/index_template?detailsList=' + $service.jsonToStr(detailsList)+'&drug_type='+that.drug_type +'&prescription_price=' + that.prescription_price)
        }else if (index == 3) { //生成处方 （已开）
            console.log(prescriptionListlength)
            if (prescriptionListlength.length >= 5) {
                $service.showToast('处方不能超过5个');
                return;
            }
            if (that.drug_type == 1) { //1中药
                var list = druglistStorage_z;
            } else {
                var list = druglistStorage_x;
            }
            if (list.length == 0) {
                $service.showToast('请先开处方');
                return;
            }
            if(that.drug_type == 1){
                this.setData({
                    isdetalis :true
                })
            }else{
                this.doctorSide_personal_prescription_addInquiryLogPrescription()
            }
        }else if(index == 4){//取消
            this.setData({
                isdetalis :false
            })
        }else if(index == 5){//中药生成处方
            if ($service.isUndefinedAndEmpty(that.prescription_taking)) {
                $service.showToast('请选择服用方法');
                return;
            }
            if ($service.isUndefinedAndEmpty(that.prescription_num)) {
                $service.showToast('请输入付数');
                return;
            }
            this.doctorSide_personal_prescription_addInquiryLogPrescription()
        }
    },

    //查询是否与已开药物发生冲突回调
    doctorSide_personal_prescription_getIncompatibility_back: function(jsonBack) {
        var data = $service.strToJson(jsonBack.data);
        if (data.code == '200') {
            if (that.drug_type == 1) { //1中药
                druglistStorage_z.push(StorageJosn)
                wx.setStorageSync("druglistStorage_z" + doctor_id, $service.jsonToStr(druglistStorage_z))
            } else { //2西药
                if (druglistStorage_x.length >= 5) {
                    $service.showToast('最多5个');
                } else {
                    druglistStorage_x.push(StorageJosn)
                }
                console.log(druglistStorage_x)
                wx.setStorageSync("druglistStorage_x" + doctor_id, $service.jsonToStr(druglistStorage_x))
            }
            this.getdruglistStorage()
            this.setData({
                isshow :0
            })
        } else {
            $service.showToast(data.info);
        }
    },
    //开药（生成处方）
    doctorSide_personal_prescription_addInquiryLogPrescription() {
        $service.showToast('正在生成中，请勿重复点击');
        var this_ = this;
        if (that.drug_type == 1) { //1中药
            var list = druglistStorage_z;
        } else {
            var list = druglistStorage_x;
        }
        var jsonData = {
            "hospital_id": hospital_id, //医院id
            "detailsList": $service.jsonToStr(list), //药品列表
            "doctor_id": doctor_id, //医生主键 0为公告模板
            "prescription_type": that.drug_type, //处方类型 1中药 2西药
            "prescription_price": that.prescription_price, //	处方金额
            "log_id": log_id, //问诊id
            "user_type": inquiryMap.join_type,
            "user_id": inquiryMap.join_id,
            "inquiry_patient_id": inquiryMap.inquiry_patient_id
        }
        if (that.drug_type == 1) { //1中药
            jsonData.prescription_taking = that.prescription_taking;
            jsonData.prescription_requirements = that.prescription_requirements;
            jsonData.prescription_num = that.prescription_num;
        }
        var jsonAjax = {
            "url": "doctorSide_personal_prescription_addInquiryLogPrescription.do",
            "jsonData": jsonData,
        }
        $service.getAjaxData(jsonAjax, function(jsonObj) {
            var selToID='';
            if(inquiryMap.join_type == 1){
                 selToID = "U" + inquiryMap.join_id
            }else{
                  selToID = "S" + inquiryMap.join_id
            }
            
             var sendSystemMessageMsgText ='';
            if (that.drug_type == 1) { //1中药
                var sendSystemMessageMsgText = '医生已开具中药处方'
                druglistStorage_z=[]
                wx.setStorageSync("druglistStorage_z" + doctor_id, $service.jsonToStr(druglistStorage_z))
            } else {
                var sendSystemMessageMsgText = '医生已开具西药处方'
                druglistStorage_x=[]
                wx.setStorageSync("druglistStorage_x" + doctor_id, $service.jsonToStr(druglistStorage_x))
            }
            $service.showToast('已生成成功');
            wx.txTic.sendCustomMessage(selToID,6)
            wx.txTic.sendSystemMessageMsg(selToID,sendSystemMessageMsgText);
            this_.setData({
                isdetalis :false
            })
            setTimeout(function() {
                wx.navigateBack({
                    delta: 1
                })
            }, 1000);
        });
    },
    //删除、编辑
    storagelist(e) {
        var index = e.currentTarget.dataset.index; //下标
        var num = e.currentTarget.dataset.num; //1编辑 2删除
        if (num == 1) {
            that.isshow = "1";
            var Map = that.getdruglistStoragelist[index]
            if(that.drug_type == 1){
                this.setData({
                    details_usage: Map.details_usage,
                    details_consumption_util: Map.details_consumption_util,
                    details_consumption: Map.details_consumption,
                    isshow : that.isshow
                })
            }else{
                this.setData({
                    details_usage: Map.details_usage,
                    details_consumption_util: Map.details_consumption_util,
                    details_frequency: Map.details_frequency,
                    details_frequency_str: Map.details_frequency_str,
                    details_consumption: Map.details_consumption,
                    details_day: Map.details_day,
                    details_num: Map.details_num,
                    details_entrust: Map.details_entrust,
                    isshow : that.isshow
                })
            }
        } else {
            if (that.drug_type == 1) { //1中药
                druglistStorage_z.splice(index, 1)
                wx.setStorageSync("druglistStorage_z" + doctor_id, $service.jsonToStr(druglistStorage_z))
            } else {
                druglistStorage_x.splice(index, 1)
                wx.setStorageSync("druglistStorage_x" + doctor_id, $service.jsonToStr(druglistStorage_x))
            }
            this.getdruglistStorage()
        }
    },
    //返回上一页
    blck(e){
        wx.redirectTo({
           url:'../index_choose_drugs/index_choose_drugs'
        })
    },
    jisuanxiyaochufangshuliang(){
     var details_consumption=this.data.details_consumption
      // var selectionunitNum=this.data.selectionunit
      var drug_packaging_num=this.data.drug_packaging_num
      var details_day=this.data.details_day
      var frequency_num=this.data.frequency_num
      var frequency_day_num=this.data.frequency_day_num

      //每次用量
      var yongliang = details_consumption
      //服用小时数
      var day = details_day * 24;
      if (yongliang > 0 && day > 0) {
        //频率每次数量
        //var frequency_num =
        console.log("频率每次数量" + frequency_num);
        //时间间隔频率
        //var frequency_day_num 
        console.log("时间间隔频率" + frequency_day_num);
        //选择的单位
        //var index = $(".xyshowC_details_consumption_util").find("option:selected").attr("index");
        console.log("选择的单位" + selectionunitNum);
        //包装单位最小数量为1
        if (drug_packaging_num == 0) {
          drug_packaging_num = 1;
        }
        console.log("包装单位" + drug_packaging_num);

        var drug_weight_num = $service.strToFloat(westernMedicinePrescriptionComputingObj.drug_weight_num).toFixed(4)
        var drug_volume_num = $service.strToFloat(westernMedicinePrescriptionComputingObj.drug_volume_num).toFixed(4)

        var unitNum = 0;//一个包装单位数量
        if (selectionunitNum == "1") {
          unitNum = drug_weight_num*drug_packaging_num;
        } else if (selectionunitNum == "2") {
          unitNum = drug_volume_num*drug_packaging_num;
        } else if (selectionunitNum == "3") {
          unitNum = drug_packaging_num
        }
        unitNum = unitNum.toFixed(4);

        console.log("一个包装单位数量" + unitNum);
        //按服用小时数/时间间隔频率*频率每次数量=总服用的次数
        var frequency = day / frequency_day_num * frequency_num
        console.log("总服用的次数" + frequency);
        //总服用次数*每次用量=总服用量
        var allNum = frequency * yongliang;
        console.log("总服用量" + allNum);
        //总服用量/一个包装单位数量=包装单位量=药品数量
        var drugQuantity = allNum / unitNum
        console.log("药品数量" + drugQuantity);
        console.log("药品数量向上取整" + Math.ceil(drugQuantity));
        this.setData({
          details_num: Math.ceil(drugQuantity)
        })
      }
    }
})
